//获取应用实例
const app = getApp()
import api from '../../utils/api'

Page({
  data: {
    banners: [], //banner集合
    indicatorDots: true, //banner
    autoplay: true, //banner
    interval: 5000, //banner
    duration: 1000, //banner
    goods: [], //首页所有数据
    currentTab: 0, //判断tab选中
    dataCount: 0, //购物车显示数量
    hidden: false,
    cartHidden: true,
    food: {}, //可定半份的菜临时变量
    rate: 0, //打折费率
    curNav: 0, //左侧餐别列表选中
    carArray: [], //购物车
    carHalfArray: [], //小份购物车
    boxHeight:0,
    ballBottom: 80,//移动
    ballRight: '70%',
    screenHeight: 0,
    screenWidth: 0,
  },
  ballMoveEvent: function (e) {
    console.log('我被拖动了....')
    var touchs = e.touches[0];
    var pageX = touchs.pageX;
    var pageY = touchs.pageY;
    console.log('pageX: ' + pageX)
    console.log('pageY: ' + pageY)
    //防止坐标越界,view宽高的一般
    if (pageX < 30) return;
    if (pageX > this.data.screenWidth - 30) return;
    if (this.data.screenHeight - pageY <= 30) return;
    if (pageY <= 30) return;
    //这里用right和bottom.所以需要将pageX pageY转换
    var x = this.data.screenWidth - pageX - 30;
    var y = this.data.screenHeight - pageY - 30;
    console.log('x: ' + x)
    console.log('y: ' + y)
    this.setData({
      ballBottom: y,
      ballRight: x
    });
  },
  //点击事件
  ballClickEvent: function () {
    console.log('点击了....')
  },
  onShow() {
    let cartGoods = app.globalData.cartGoods;
    let cartHalfGoods = app.globalData.cartHalfGoods;
    let dataCount = 0;
    cartGoods.filter(item => {
      dataCount += item.num;
    });
    cartHalfGoods.filter(item => {
      dataCount += item.num;
    });
    this.setData({
      carArray: cartGoods,
      carHalfArray: cartHalfGoods,
      dataCount: dataCount,
      goods: app.globalData.stoves
    });

  },
  onLoad: function(options) {
    try {
      //加载数据发起请求
      this.initData();
      this.updUser();
      let res = wx.getSystemInfoSync();
      let boxHeight = res.windowHeight;
      this.setData({
        'boxHeight': boxHeight
      });
      //获取屏幕宽高
      var _this = this;
      wx.getSystemInfo({
        success: function (res) {
          _this.setData({
            screenHeight: res.windowHeight,
            screenWidth: res.windowWidth,
          });
        }
      });

    } catch (e) {

    }
  },
  _swichNav: function(e) { //切换选项卡
    this.setData({
      currentTab: e.currentTarget.dataset.current
    })
  },

  /**
   * 跳转指定的餐别
   */
  selectMenu: function(e) {
    var index = e.currentTarget.dataset.itemIndex;
    this.setData({
      toView: 'order' + index.toString()
    })
  },
  /**
   * 根据类别查询数据
   */
  selectTypeList: function(e) {
    wx.showLoading({
      title: '正在加载...',
    })

    var stoveIndex = e.currentTarget.dataset.stoveIndex;
    var mealIndex = e.currentTarget.dataset.mealsIndex;
    var typeCode = e.currentTarget.dataset.typeCode;

    var mealsName = "";
    if (mealIndex == 0) {
      mealsName = "早餐";
    }
    if (mealIndex == 1) {
      mealsName = "午餐";
    }
    if (mealIndex == 2) {
      mealsName = "晚餐";
    }
    var { goods,currentTab } = this.data;

    let meals = goods[currentTab].meals;
    for (let j = 0; j < meals.length; j++) {
      if (meals[j].mealNo == mealIndex + 1) {
        meals[j].selected = true;
        let recipes = meals[j].recipes;
        for (let k = 0; k < recipes.length; k++) {
          if (recipes[k].type_code == typeCode) {
            recipes[k].show = true;
          } else {
            recipes[k].show = false;
          }
        }
      } else {
        meals[j].selected = false;
        let recipes = meals[j].recipes;
        for (let k = 0; k < recipes.length; k++) {
          recipes[k].show = false;
        }
      }
      
    }

    this.setData({
      goods: goods,
    })
    app.globalData.stoves = goods;
    wx.hideLoading();

  },
  //小份移除商品
  decreaseSmalCart: function(e) {
    var tabIndex = this.data.food.tabIndex;
    var mealIndex = this.data.food.mealIndex;
    var foodIndex = this.data.food.foodIndex;
    this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].countSum--;
    this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].xfCount--;

    var id = this.data.food.id;

    var carList = this.data.carHalfArray;
    for (var m = 0; m < carList.length; m++) {
      if (carList[m].id == id) {
        carList.splice(m, 1); // a需要删除的位置,b删除几个
        break;
      }
    }

    this.data.food.xfCount--;
    this.setData({
      dataCount: this.data.dataCount - 1,
      carHalfArray: carList,
      goods: this.data.goods,
      food: this.data.food,
    })

    app.globalData.cartHalfGoods = carList;
    app.globalData.stoves = this.data.goods;
  },
  //大份移除商品
  decreaseBigCart: function(e) {
    var tabIndex = this.data.food.tabIndex;
    var mealIndex = this.data.food.mealIndex;
    var foodIndex = this.data.food.foodIndex;

    this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].countSum--;
    this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].count--;

    this.data.food.count--;
    var id = this.data.food.id;
    var num = this.data.food.count;
    var price = this.data.food.price;
    var cook_img = this.data.food.cook_img;
    var name = this.data.food.name;
    var meals = this.data.food.meals;
    var half_state = this.data.food.half_state;
    var obj = {
      id: id,
      num: num,
      name: name,
      price: price,
      meals: meals,
      cook_img: cook_img,
      checked: true,
      sfxf: 'n',
      tabIndex: tabIndex,
      mealIndex: mealIndex,
      foodIndex: foodIndex,
      half_state: half_state
    };
    var carList = this.data.carArray.filter(item => item.id != id);
    carList.push(obj);
    for (var m = 0; m < carList.length; m++) {
      if (carList[m].num == 0) {
        carList.splice(m, 1); // a需要删除的位置,b删除几个
      }
    }
    this.setData({
      dataCount: this.data.dataCount - 1,
      carArray: carList,
      goods: this.data.goods,
      food: this.data.food
    })

    app.globalData.cartGoods = carList;
    app.globalData.stoves = this.data.goods;
  },
  //移除商品
  decreaseCart: function(e) {
    var tabIndex = e.currentTarget.dataset.tabindex;
    var mealIndex = e.currentTarget.dataset.parentindex;
    var foodIndex = e.currentTarget.dataset.foodindex;

    this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].Count--;

    var id = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].id;
    var num = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].Count;
    var price = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].price;
    var cook_img = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].cook_img;
    var name = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].name;
    var meals = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].meals;
    var half_state = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].half_state;
    var obj = {
      id: id,
      num: num,
      name: name,
      price: price,
      meals: meals,
      cook_img: cook_img,
      checked: true,
      sfxf: 'n',
      tabIndex: tabIndex,
      mealIndex: mealIndex,
      foodIndex: foodIndex,
      half_state: half_state
    };

    var carList = this.data.carArray.filter(item => item.id != id);
    carList.push(obj);
    for (var m = 0; m < carList.length; m++) {
      if (carList[m].num == 0) {
        carList.splice(m, 1); // a需要删除的位置,b删除几个
      }
    }
    this.setData({
      dataCount: this.data.dataCount - 1,
      carArray: carList,
      goods: this.data.goods
    })

    app.globalData.cartGoods = carList;
    app.globalData.stoves = this.data.goods;
  },
  showAddCart(e) {
    var food = e.currentTarget.dataset.food;
    var tabIndex = e.currentTarget.dataset.tabindex;
    var mealIndex = e.currentTarget.dataset.parentindex;
    var foodIndex = e.currentTarget.dataset.foodindex;
    food.tabIndex = tabIndex;
    food.mealIndex = mealIndex;
    food.foodIndex = foodIndex;

    let xfPrice = (food.price * this.data.rate).toFixed(2)
    if (!food["count"]) {
      food.count = 0;
    }
    if (!food["xfCount"]) {
      food.xfCount = 0;
    }
    food.xfPrice = xfPrice;
    this.setData({
      cartHidden: false,
      food: food
    })
  },
  //小份添加到购物车
  addSmalCart(e) {
    var tabIndex = this.data.food.tabIndex;
    var mealIndex = this.data.food.mealIndex;
    var foodIndex = this.data.food.foodIndex;
    if (this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex]["countSum"]) {
      this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].countSum++;
    } else {
      this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].countSum = 1;
    }
    if (this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex]["xfCount"]) {
      this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].xfCount++;
    } else {
      this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].xfCount = 1;
    }


    var id = this.data.food.id;
    var num = 1;
    var price = this.data.food.price;
    var cook_img = this.data.food.cook_img;
    var name = this.data.food.name;
    var meals = this.data.food.meals;
    var half_state = this.data.food.half_state;
    var obj = {
      id: id,
      num: num,
      name: name + "--小份",
      price: (price * this.data.rate).toFixed(2),
      meals: meals,
      cook_img: cook_img,
      checked: true,
      sfxf: 'y',
      tabIndex: tabIndex,
      mealIndex: mealIndex,
      foodIndex: foodIndex,
      half_state
    };
    var carList = this.data.carHalfArray;
    carList.push(obj);

    this.data.food.xfCount++;
    this.setData({
      dataCount: this.data.dataCount + 1,
      carHalfArray: carList,
      goods: this.data.goods,
      food: this.data.food,
    })

    app.globalData.cartHalfGoods = carList;
    app.globalData.stoves = this.data.goods;
  },
  //大份添加到购物车
  addBigCart(e) {
    var tabIndex = this.data.food.tabIndex;
    var mealIndex = this.data.food.mealIndex;
    var foodIndex = this.data.food.foodIndex;

    if (this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex]["countSum"]) {
      this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].countSum++;
    } else {
      this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].countSum = 1;
    }

    if (this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex]["count"]) {
      this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].count++;
    } else {
      this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].count = 1;
    }
    this.data.food.count++;

    var id = this.data.food.id;
    var num = this.data.food.count;
    var price = this.data.food.price;
    var cook_img = this.data.food.cook_img;
    var name = this.data.food.name;
    var meals = this.data.food.meals;
    var half_state = this.data.food.half_state;
    var obj = {
      id: id,
      num: num,
      name: name,
      price: price,
      meals: meals,
      cook_img: cook_img,
      checked: true,
      sfxf: 'n',
      tabIndex: tabIndex,
      mealIndex: mealIndex,
      foodIndex: foodIndex,
      half_state: half_state
    };
    var carList = this.data.carArray.filter(item => item.id != id)
    carList.push(obj)

    this.setData({
      dataCount: this.data.dataCount + 1,
      carArray: carList,
      goods: this.data.goods,
      food: this.data.food
    })

    app.globalData.cartGoods = carList;
    app.globalData.stoves = this.data.goods;
  },
  //添加到购物车
  addCart(e) {
    var tabIndex = e.currentTarget.dataset.tabindex;
    var mealIndex = e.currentTarget.dataset.parentindex;
    var foodIndex = e.currentTarget.dataset.foodindex;

    if (this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex]["Count"]) {
      this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].Count++;
    } else {
      this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].Count = 1;
    }

    var id = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].id;
    var num = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].Count;
    var price = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].price;
    var cook_img = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].cook_img;
    var name = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].name;
    var meals = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].meals;
    var half_state = this.data.goods[tabIndex].meals[mealIndex].recipes[foodIndex].half_state;
    var obj = {
      id: id,
      num: num,
      name: name,
      price: price,
      meals: meals,
      cook_img: cook_img,
      checked: true,
      sfxf: 'n',
      tabIndex: tabIndex,
      mealIndex: mealIndex,
      foodIndex: foodIndex,
      half_state
    };
    var carList = this.data.carArray.filter(item => item.id != id)
    carList.push(obj)
    this.setData({
      dataCount: this.data.dataCount + 1,
      carArray: carList,
      goods: this.data.goods
    })

    app.globalData.cartGoods = carList;
    app.globalData.stoves = this.data.goods;
  },
  /**
   * 获取组分类
   */
  toTypeList(goods) {
    for (let i = 0; i < goods.length; i++) {
      let meals = goods[i].meals;
      for (let j = 0; j < meals.length; j++) {
        if (meals[j].mealNo == "1") {
          meals[j].selected = true;
        } else {
          meals[j].selected = false;
        }
        let recipes = meals[j].recipes;
        let typeList = [];
        for (let k = 0; k < recipes.length; k++) {
          if (recipes[k].meals == "早餐") {
            recipes[k].show = true;
          } else {
            recipes[k].show = false;
          }

          let typeItem = {
            "code": recipes[k].type_code,
            "name": recipes[k].type_name
          };
          if (typeList.length == 0) {
            typeList.push(typeItem);
          } else {
            let flag = false;
            for (let y = 0; y < typeList.length; y++) {
              if (typeList[y].code == typeItem.code) {
                flag = true;
                break;
              }
            }
            if (!flag) {
              typeList.push(typeItem);
            }
          }
        }
        meals[j].typeList = typeList;
      }
    }
    return goods;
  },
  initData() {
    let user = wx.getStorageSync("user");
    if (!user.bh) {
      wx.redirectTo({
        url: '../login/login',
      })
    }

    let _this = this;
    let param = {
      'patientId': user.bh
    };
    api.POST({
      url: 'homeH5.action',
      params: param,
      success: function(res) {
        let banner = res.data.data.banner;
        let rate = res.data.data.rate;
        let stoves = _this.toTypeList(res.data.data.stoves);
        _this.setData({
          banners: banner,
          goods: stoves,
          rate: rate
        })
        app.globalData.stoves = stoves;
      },
      fail: function() {
        wx.showToast({
          icon: 'none',
          title: '请求失败',
        })
      },
    })
  },
  cancel: function() {
    this.setData({
      hidden: true,
      cartHidden: true
    });
  },
  //点击左侧 tab ，右侧列表相应位置联动 置顶
  switchRightTab: function(e) {
    var index = e.currentTarget.dataset.index;
    var goods = this.showTypeList(index);
    this.setData({
      curNav: index,
      goods: goods
    })
    app.globalData.stoves = goods;
  },
  showTypeList(mealIndex) {
    var mealsName = "";
    if (mealIndex == 0) {
      mealsName = "早餐";
    }
    if (mealIndex == 1) {
      mealsName = "午餐";
    }
    if (mealIndex == 2) {
      mealsName = "晚餐";
    }
    var {
      goods,
      currentTab
    } = this.data;

    let meals = goods[currentTab].meals;
    for (let j = 0; j < meals.length; j++) {
      if (meals[j].mealNo == mealIndex + 1) {
        meals[j].selected = true;
      } else {
        meals[j].selected = false;
      }
      let recipes = meals[j].recipes;
      for (let k = 0; k < recipes.length; k++) {
        if (recipes[k].meals == mealsName) {
          recipes[k].show = true;
        } else {
          recipes[k].show = false;
        }
      }
    }
    return goods;
  },
  updUser() {
    let user = wx.getStorageSync("user");
    if (!user.bh) {
      wx.redirectTo({
        url: '../login/login',
      })
      return;
    }
    let param = { "patientId": user.bh };
    api.POST({
      url: 'login.action',
      params: param,
      success: function (res) {
        let success = res.data.success;
        if (success == "true") {
          let user = res.data.data[0]; //replace(/\s+/g, '')
          user.bh = user.bh.replace(/\s+/g, '');
          wx.setStorage({
            key: 'user',
            data: user
          })
        } else {
          wx.showToast({
            icon: 'none',
            title: res.data.msg,
            duration: 5000
          })
          wx.clearStorage({
            success: function () {
              wx.redirectTo({
                url: '../login/login'
              })
            }
          })
        }
      },
      fail: function () {
        wx.showToast({
          icon: 'none',
          title: '请求失败',
          duration: 5000
        })
      },
    })

  },
  showNutrition:function(e){
    var tabIndex = e.currentTarget.dataset.tabindex;
    var mealIndex = e.currentTarget.dataset.parentindex;
    var foodIndex = e.currentTarget.dataset.foodindex;

    var food = e.currentTarget.dataset.food;
    let xfPrice = (food.price * this.data.rate).toFixed(2);
    food.xfPrice = xfPrice;
    food.tabIndex = tabIndex;
    food.mealIndex = mealIndex;
    food.foodIndex = foodIndex;

    app.globalData.food = food;
    wx.navigateTo({
      url: '../show/show',
    })
  },

  getLoginSession:function(){
    wx.login({
      success(res) {
        let param = {
          "code": res.code
        }
        api.POST({
          url: 'code2Session.action',
          params: param,
          success: function (res) {
            console.log(res + "哈哈哈哈哈")
          },
          fail: function () {
            wx.showToast({
              icon: 'none',
              title: '提交失败',
            })
          },
        })
      }
    })
  }
})